package com.boguan.web.controller.system;

import java.io.*;
import java.util.*;


import com.boguan.common.utils.MessageUtils;
import com.boguan.common.utils.SecurityUtils;
import com.boguan.common.utils.StringUtils;
import com.boguan.device.service.IDeviceService;
import com.boguan.framework.manager.AsyncManager;
import com.boguan.framework.manager.factory.AsyncFactory;
import com.boguan.system.domain.dto.UserFeedBackDto;
import com.boguan.system.domain.vo.Register;
import com.boguan.system.service.ISysUserService;
import com.boguan.web.controller.common.CaptchaVerify;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.boguan.common.constant.Constants;
import com.boguan.common.core.domain.AjaxResult;
import com.boguan.common.core.domain.entity.SysMenu;
import com.boguan.common.core.domain.entity.SysUser;
import com.boguan.common.core.domain.model.LoginBody;
import com.boguan.common.core.domain.model.LoginUser;
import com.boguan.common.utils.ServletUtils;
import com.boguan.framework.web.service.SysLoginService;
import com.boguan.framework.web.service.SysPermissionService;
import com.boguan.framework.web.service.TokenService;
import com.boguan.system.service.ISysMenuService;
import org.springframework.web.multipart.MultipartFile;



/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
@Api(tags = "登录相关")
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private CaptchaVerify captchaVerify;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword());
        ajax.put(Constants.TOKEN, token);
        ajax.put("username", loginBody.getUsername());
        return ajax;
    }

    @ApiOperation("web登录")
    @PostMapping("/loginWeb")
    public AjaxResult loginWeb(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        ajax.put("username", loginBody.getUsername());
        return ajax;
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("验证码登录")
    @PostMapping("/verification/code/login")
    public AjaxResult loginCode(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNull(loginBody.getCode()) || !captchaVerify.verify(loginBody.getCode(), Constants.LOGIN_CODE + loginBody.getPhoneNumber())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getPhoneNumber(), Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            return AjaxResult.error("短信验证码信息错误");
        }
        SysUser user = userService.selectUserByUserPhone(loginBody.getPhoneNumber());
        // 生成令牌
        String token = loginService.loginCode(loginBody.getPhoneNumber(), loginBody.getCode());
        ajax.put(Constants.TOKEN, token);
        ajax.put("username", user.getUserName());
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation("获取用户信息")
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if(loginUser !=null){
            SysUser user = loginUser.getUser();
            // 角色集合
            Set<String> roles = permissionService.getRolePermission(user);
            // 权限集合
            Set<String> permissions = permissionService.getMenuPermission(user);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("user", user);
            ajax.put("roles", roles);
            ajax.put("permissions", permissions);
            return ajax;
        }
        return AjaxResult.error("没有登录请先登录");

    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @ApiOperation("获取路由信息")
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        if(loginUser !=null){
            SysUser user = loginUser.getUser();
            List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());

            return AjaxResult.success(menuService.buildMenus(menus));

        }
        return AjaxResult.error("没有登录请先登录");

    }


    /**
     * 忘记密码
     */
    @ApiOperation("忘记密码")
    @PostMapping("/retrieve/password")
    public AjaxResult retrievePassword(@RequestBody Register register) {
        SysUser user = userService.selectUserByUserName(register.getUsername());
        if (StringUtils.isNull(user)) {
            return AjaxResult.error("用户名不存在");
        }
        if(!register.getNewPassword().equals(register.getConfirmPassword())){
            return AjaxResult.error("两次密码不一致");
        }
//        else if (!user.getPhonenumber().equals(register.getPhonenumber())) {
//            return AjaxResult.error("您输入的手机号与您预留的不一致");
//        }
//        else if (StringUtils.isNull(register.getCode()) ||
//                !captchaVerify.verify(register.getCode(), Constants.RETRIEVE_PASSWORD_CODE + user.getPhonenumber())) {
//            return AjaxResult.error("验证码信息不正确");
//        }
        //密码更新
        user.setPassword(SecurityUtils.encryptPassword(register.getNewPassword()));
        return AjaxResult.success(userService.updateUser(user));
    }

    @ApiOperation("修改密码")
    @PostMapping("/modify/password")
    public AjaxResult modifyPassword(@RequestBody Register register){

        SysUser user = userService.selectUserByUserName(register.getUsername());
        if (StringUtils.isNull(user)) {
            return AjaxResult.error("用户名不存在");
        }

        if(!SecurityUtils.matchesPassword(register.getOldPassword(),user.getPassword())){
            return  AjaxResult.error("原密码错误");
        }
        if(!register.getNewPassword().equals(register.getConfirmPassword())){
            return AjaxResult.error("两次密码不一致");
        }
        user.setPassword(SecurityUtils.encryptPassword(register.getNewPassword()));
        userService.updateUser(user);
        return AjaxResult.success();
    }

    @ApiOperation("用户反馈")
    @PostMapping("/userFeedBack")
    public AjaxResult userFeedBack(UserFeedBackDto dto, MultipartFile imgfile) throws IOException {
        if(imgfile!=null){
            String filename= System.currentTimeMillis()+ new Random().nextInt(99999)+"";
            String sub = imgfile.getOriginalFilename().substring(imgfile.getOriginalFilename().lastIndexOf("."));
            String image =filename+sub;
            File file = new File("/home/power/power-ui/distweb/upload/"+image);

            imgfile.transferTo(file);
            dto.setImage(file.getAbsolutePath());
        }

        userService.addUserFeedBack(dto);
        return AjaxResult.success();
    }

    @ApiOperation("大屏显示")
    @GetMapping("getBigScreen")
    public AjaxResult getBigScreen(){

       return AjaxResult.success(deviceService.bigScreen());
    }






}
